package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.TaxConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpClientUtil;
import com.ruoyi.system.domain.WaterMeter;
import com.ruoyi.system.domain.WaterYcmeterDatahistory;
import com.ruoyi.system.domain.tax.FluxPressureData;
import com.ruoyi.system.domain.xtkj.*;
import com.ruoyi.system.service.IWaterInterfaceService;
import com.ruoyi.system.service.IWaterMeterService;
import com.ruoyi.system.service.IWaterYcmeterDatahistoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @description todo
 * @data 2025/10/16 16:55
 */
@Service
public class WaterInterfaceServiceImpl implements IWaterInterfaceService {

    private static final Logger log = LoggerFactory.getLogger(WaterInterfaceServiceImpl.class);
    @Autowired
    private IWaterYcmeterDatahistoryService historyService;
    @Autowired
    private IWaterMeterService waterMeterService;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private ObjectMapper objectMapper;
    private String accessToken;
    private long tokenExpiryTime;

    @Override
    public int syncXTKJWaterMeterData(WaterMeter waterMeter, String startTime, String endTime) {
//        String startTime = time;
//        String endTime = DateUtils.getTime();
        String deviceId = waterMeter.getDeviceId();
        if(StringUtils.isEmpty(deviceId)){
            return 1;
        }
        XTApiResponse<PageDataResponse<FlowMeterHistoryData>> response = getFlowMeterHistoryData(deviceId, startTime, endTime, 1, 289);
        PageDataResponse<FlowMeterHistoryData> pageData = response.getData();
        if (pageData == null || pageData.getDataInfo() == null || pageData.getDataInfo().isEmpty()) {
            return 0;
        }
        List<FlowMeterHistoryData> flowMeterHistoryDataList = pageData.getDataInfo();
        if (!flowMeterHistoryDataList.isEmpty()){
            FlowMeterHistoryData firstData = flowMeterHistoryDataList.get(flowMeterHistoryDataList.size()-1); // 获取最后一条数据
            WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
            dataHistory.setMeterNo(waterMeter.getMeterNo());
            dataHistory.setUserId(waterMeter.getUserId());
//            dataHistory.setUserName(waterMeter.getUserName());
            dataHistory.setMeterType("0"); // 远传表
            String readDate = firstData.getReadDate().substring(0, 16);
            dataHistory.setReadDate(readDate); // 抄表时间
            dataHistory.setLastReading(Double.valueOf(waterMeter.getCurrentReading())); // 上次抄表数
            dataHistory.setCurrentReading(firstData.getPositiveAccumulativeFlow()); // 累计流量
            dataHistory.setPressure(firstData.getPressure()); // 压力
            dataHistory.setFlowRate(firstData.getPositiveFlowRate()); // 瞬时流量
            historyService.insertWaterYcmeterDatahistory(dataHistory); // 添加历史数据
            // 更新表具档案 实时数据
            waterMeter.setReadDate(readDate);
            waterMeter.setCurrentReading(firstData.getPositiveAccumulativeFlow().toString());
            waterMeter.setPressure(firstData.getPressure().toString());
            waterMeter.setFlux(firstData.getPositiveFlowRate().toString());
            return waterMeterService.updateWaterMeterNo(waterMeter);
        }else{
            log.warn("水表{}流量压力数据为空", waterMeter.getMeterNo());
            return 0;
        }
    }

    @Override
    public void syncCYWaterMeterRealData(WaterMeter waterMeter,WaterYcmeterDatahistory realData) {
        WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
        dataHistory.setMeterNo(waterMeter.getMeterNo());
        dataHistory.setUserId(waterMeter.getUserId());
        dataHistory.setMeterType("0"); // 远传表
        dataHistory.setReadDate(realData.getReadDate()); // 抄表时间
        if(StringUtils.isEmpty(waterMeter.getCurrentReading())){
            dataHistory.setLastReading(0.0);
        }else{
            dataHistory.setLastReading(Double.valueOf(waterMeter.getCurrentReading())); // 上次抄表数
        }
        try {
            dataHistory.setCurrentReading(realData.getCurrentReading()); // 累计流量
            dataHistory.setPressure(realData.getPressure()); // 压力
            dataHistory.setFlowRate(realData.getFlowRate()); // 瞬时流量
            historyService.insertWaterYcmeterDatahistory(dataHistory); // 添加历史数据
            // 更新表具档案 实时数据
            waterMeter.setReadDate(realData.getReadDate());
            waterMeter.setCurrentReading(realData.getCurrentReading().toString());
            waterMeter.setPressure(realData.getPressure().toString());
            waterMeter.setFlux(realData.getFlowRate().toString());
            waterMeterService.updateWaterMeterNo(waterMeter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pushCYWaterMeterData(FluxPressureData fluxPressureData) {
        String meterNo = fluxPressureData.getMeterNo();
        WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
        dataHistory.setMeterNo(meterNo);
        dataHistory.setMeterType("0"); // 远传表
        dataHistory.setReadDate(fluxPressureData.getReadtime()); // 抄表时间
        dataHistory.setCurrentReading(fluxPressureData.getTotalFlux()); // 累计流量
        dataHistory.setPressure(fluxPressureData.getPressure()); // 压力
        dataHistory.setFlowRate(fluxPressureData.getFlux()); // 瞬时流量
        historyService.insertWaterCyMeterData(dataHistory); // 添加历史数据
    }

    @Override
    public List<WaterYcmeterDatahistory> selectCYWaterMeterData() {
        return historyService.selectWaterCyMeterDataList();
    }

    public boolean getToken(){
        String url = TaxConstants.BASE_URL + "/ApiKeyApi/GetToken";
        try {
            String requestBody = "{\"ak_key\":\"" + TaxConstants.APP_KEY + "\",\"ak_secret\":\"" + TaxConstants.APP_SECRET + "\"}";
            String responseBody = httpClientUtil.post(url, requestBody, null);
            XTApiResponse<TokenData> apiResponse = objectMapper.readValue(
                    responseBody, new TypeReference<XTApiResponse<TokenData>>() {});
            if (apiResponse.isSuccess() && apiResponse.getData() != null) {
                accessToken = apiResponse.getData().getAccessToken();
                tokenExpiryTime = System.currentTimeMillis() + apiResponse.getData().getExpiryMinutes() * 60 * 1000;
                log.info("Token获取成功，Token: {}", accessToken);
                log.info("Token获取成功，过期时间: {}", apiResponse.getData().getExpiryTime());
                return true;
            }
        } catch (Exception e) {
            log.error("获取Token时发生异常", e);
        }
        return false;
    }

    /**
     * 检查Token是否有效
     */
    private boolean isTokenValid() {
        return accessToken != null && System.currentTimeMillis() < tokenExpiryTime - 60000; // 提前1分钟刷新
    }

    /**
     * 执行api请求
     */
    private <T> XTApiResponse<PageDataResponse<T>> executePageRequest(String url, Object requestBody, Class<T> elementType) {
        try {
            String jsonBody = objectMapper.writeValueAsString(requestBody);
            Map<String, String> headers = new HashMap<>();
            if(!isTokenValid()){ // 如果Token已过期，则重新获取
                getToken();
            }
            headers.put("access-token", accessToken);
            System.err.println("请求地址："+url);
            System.err.println("请求参数："+jsonBody);
            String responseBody = httpClientUtil.post(url, jsonBody, headers);
            System.err.println(responseBody);
            // 构造分页响应类型
            JavaType pageDataType = objectMapper.getTypeFactory().constructParametricType(
                    PageDataResponse.class, elementType);
            JavaType responseType = objectMapper.getTypeFactory().constructParametricType(
                    XTApiResponse.class, pageDataType);
            return objectMapper.readValue(responseBody, responseType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 流量计实时数据
    public XTApiResponse<PageDataResponse<FlowMeterRealData>> getFlowMeterRealData(
            String pointCode, String pointName, Integer meteringType, Integer page, Integer rows) {

        Map<String, Object> requestBody = new HashMap<>();
        if (pointCode != null) {
            requestBody.put("PointCode", pointCode);
        }
        if (pointName != null) {
            requestBody.put("PointName", pointName);
        }
        if (meteringType != null) {
            requestBody.put("MeteringType", meteringType);
        }
        if (page != null) {
            requestBody.put("Page", page);
        }
        if (rows != null) {
            requestBody.put("Rows", rows);
        }

        String url = TaxConstants.BASE_URL + "/Bussiness_FlowMonitorApi/GetRealData";
        return executePageRequest(url, requestBody, FlowMeterRealData.class);
    }

    // 流量计历史数据
    public XTApiResponse<PageDataResponse<FlowMeterHistoryData>> getFlowMeterHistoryData(
            String dataPointId, String startTime, String endTime, Integer page, Integer rows) {

        Map<String, Object> requestBody = new HashMap<>();
        if (dataPointId != null) {
            requestBody.put("DataPointID", dataPointId);
        }
        if (startTime != null) {
            requestBody.put("StartTime", startTime);
        }
        if (endTime != null) {
            requestBody.put("EndTime", endTime);
        }
        if (page != null) {
            requestBody.put("Page", page);
        }
        if (rows != null) {
            requestBody.put("Rows", rows);
        }

        String url = TaxConstants.BASE_URL + "/Bussiness_FlowMonitorApi/GetHistoryData";
        return executePageRequest(url, requestBody, FlowMeterHistoryData.class);
    }
}
